package com.fruit.service.rights.impl;

import com.fruit.mapper.rights.UserRightsMapper;
import com.fruit.pojo.goods.RightConfig;
import com.fruit.pojo.rights.UserGoodsRights;
import com.fruit.pojo.rights.UserGoodsRightsHarvest;
import com.fruit.pojo.rights.UserGoodsRightsPost;
import com.fruit.service.goods.GoodsManager;
import com.fruit.service.rights.UserRightsManager;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @ClassName: UserRightsService
 * @author 葛欢欢
 * @version 2017.11.30 16:40
 */
@Slf4j
@Service
public class UserRightsService implements UserRightsManager {
	@Autowired
	private UserRightsMapper userRightsMapper;

	@Autowired
	private GoodsManager goodsManager;

	/**
	 * 权益列表
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param pam
	 *            pam
	 * @return List<UserGoodsRights>
	 */
	@Override
	public List<UserGoodsRights> userTrees(Map<String, Object> pam) {
		long systime = System.currentTimeMillis();
		log.info("【获取权益列表service方法进入时间】" + DateUtil.getTime());
		log.info("权益列表service方法 userTrees，传入的参数 pam：" + pam);
		List<Map<String, String>> unitList = goodsManager.getUnitNameByUnit();
		Map<String, String> unit = new HashMap<String, String>();
		Map<String, String> unitMap = new HashMap<String, String>();
		if (unitList != null) {
			for (int i = 0; i < unitList.size(); i++) {
				unitMap = unitList.get(i);
				unit.put((String) unitMap.get("unit"), (String) unitMap.get("name"));
			}
		}
		List<UserGoodsRights> userGoodsRightsList = userRightsMapper.fruitTreeList(pam);
		if (userGoodsRightsList != null && userGoodsRightsList.size() > 0) {
			for (int i = 0; i < userGoodsRightsList.size(); i++) {
				UserGoodsRights userGoodsRights = userGoodsRightsList.get(i);
				userGoodsRights.setUnitDesc(unit.get(userGoodsRights.getUnit()));
				userGoodsRights.setHarvestUnitDesc(unit.get(userGoodsRights.getHarvestUnit()));
//				userGoodsRights.setGoodsName(userGoodsRights.getGoodsName() + "(共" + userGoodsRights.getNum()
//						+ userGoodsRights.getUnitDesc() + ")");
				userGoodsRights.setGoodsName(userGoodsRights.getGoodsName());
				boolean isState = DateUtil.compareDate(userGoodsRights.getEndUseTime(), DateUtil.getTime());
				if (isState) { // 如果 isState为true 说明截至使用时间大于当前系统时间 那么就不过期
					userGoodsRights.setState("01");
				} else {
					userGoodsRights.setState("00");
				}
			}
		}
		log.info("结束权益列表service方法 userTrees，返回的值userGoodsRightsList" + userGoodsRightsList);
		log.info("结束时间：" + (System.currentTimeMillis() - systime) / 1000f + "秒");
		return userGoodsRightsList;
	}

	@Override
	public List<UserGoodsRights> getRightsByGstId(Map<String, Object> pam) {
		List<Map<String, String>> unitList = goodsManager.getUnitNameByUnit();
		Map<String, String> unit = new HashMap<String, String>();
		Map<String, String> unitMap = new HashMap<String, String>();
		if (unitList != null) {
			for (int i = 0; i < unitList.size(); i++) {
				unitMap = unitList.get(i);
				unit.put((String) unitMap.get("unit"), (String) unitMap.get("name"));
			}
		}
		List<UserGoodsRights> userGoodsRightsList = userRightsMapper.getGoodsRightsByGstId(pam);
		if (userGoodsRightsList != null && userGoodsRightsList.size() > 0) {
			for (int i = 0; i < userGoodsRightsList.size(); i++) {
				UserGoodsRights userGoodsRights = userGoodsRightsList.get(i);
				userGoodsRights.setUnitDesc(unit.get(userGoodsRights.getUnit()));
				userGoodsRights.setHarvestUnitDesc(unit.get(userGoodsRights.getHarvestUnit()));
//				userGoodsRights.setGoodsName(userGoodsRights.getGoodsName() + "(共" + userGoodsRights.getNum()
//						+ userGoodsRights.getUnitDesc() + ")");
				userGoodsRights.setGoodsName(userGoodsRights.getGoodsName());
				boolean isState = DateUtil.compareDate(userGoodsRights.getEndUseTime(), DateUtil.getTime());
				if (isState) { // 如果 isState为true 说明截至使用时间大于当前系统时间 那么就不过期
					userGoodsRights.setState("01");
				} else {
					userGoodsRights.setState("00");
				}
			}
		}
		return userGoodsRightsList;
	}

	/**
	 * 用户权益详情
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param id
	 *            id
	 * @return UserGoodsRights
	 */
	@Override
	public UserGoodsRights getUserGoodsRight(int id) {
		long systime = System.currentTimeMillis();
		log.info("【用户权益详情service方法进入时间】" + DateUtil.getTime());
		log.info("【用户权益详情service方法传入的参数 id：】" + id);
		List<Map<String, String>> unitList = goodsManager.getUnitNameByUnit();
		Map<String, String> unit = new HashMap<String, String>();
		Map<String, String> unitMap = new HashMap<String, String>();
		if (unitList != null) {
			for (int i = 0; i < unitList.size(); i++) {
				unitMap = unitList.get(i);
				unit.put((String) unitMap.get("unit"), (String) unitMap.get("name"));
			}
		}
		UserGoodsRights rights = userRightsMapper.find(id);
		if (rights == null) {
			return null;
		}
		rights.setUserGoodsRightsHarvests(userRightsMapper.findUserGoodsRightsHarvest(id));
		rights.setUnitDesc(unit.get(rights.getUnit()));
		rights.setHarvestUnitDesc(unit.get(rights.getHarvestUnit()));
		rights.setEndUseTime(DateUtil.ChTime(rights.getEndUseTime()));
		log.info("【用户权益详情service，返回值：】" + rights);
		log.info("【用户权益详情结束时间：】" + (System.currentTimeMillis() - systime) / 1000f + "秒");
		return rights;
	}

	/**
	 * 查询每个大类的统计百分比
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param uGRights
	 *            uGRights
	 * @param tradeId
	 *            tradeId
	 * @return Map<String, Object>
	 */
	@Override
	public Map<String, Object> insertGoodsRight(List<UserGoodsRights> uGRights, String tradeId) {
		long systime = System.currentTimeMillis();
		log.info("【查询每个大类的统计百分比service方法进入时间】" + DateUtil.getTime());
		log.info("【查询每个大类的统计百分比service方法传入的参数 uGRights：】" + uGRights + "【   tradeId：】" + tradeId);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			int rightId = 0;
			for (int j = 0; j < uGRights.size(); j++) {
				UserGoodsRights goodsRights = uGRights.get(j);
				int num = userRightsMapper.insertGoodsRight(goodsRights);
				List<UserGoodsRightsHarvest> ugthList = new ArrayList<UserGoodsRightsHarvest>();
				String[] expectHarvest = goodsRights.getExpectHarvests().split(","); // 产量
				String[] expectHarvestTime = goodsRights.getExpectHarvestTimes().split(","); // 预计产量时间
				for (int i = 0; i < expectHarvest.length; i++) {
					UserGoodsRightsHarvest urh = new UserGoodsRightsHarvest();
					urh.setExpectHarvest(new BigDecimal(expectHarvest[i]));
					urh.setExpectHarvestTime(expectHarvestTime[i]);
					urh.setUserGoodsRightsId((int) goodsRights.getId());
					ugthList.add(urh);
				}
				userRightsMapper.insertGoodsRightHarvest(ugthList);
				rightId += num;
			}
			if (rightId != uGRights.size()) { // 如果返回的行数和 list集合的个数相等 那么就说明
												// 都插入进去啦
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "save_error", "新增失败!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", "添加成功"));
			log.info("【查询每个大类的统计百分比service，返回值：】" + resMap);
			log.info("【查询每个大类的统计百分比结束时间：】" + (System.currentTimeMillis() - systime) / 1000f + "秒");
			return resMap;
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result",
					ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		} finally {
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}

	}

	/**
	 * 查询权益的预计产量信息
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param id
	 *            id
	 * @return List<UserGoodsRightsHarvest>
	 */
	@Override
	public List<UserGoodsRightsHarvest> findUserGoodsRightsHarvest(int id) {
		long systime = System.currentTimeMillis();
		log.info("【查询权益的预计产量信息service方法进入时间】" + DateUtil.getTime());
		log.info("【查询权益的预计产量信息service方法传入的参数 id：】" + id);
		List<UserGoodsRightsHarvest> ugList = userRightsMapper.findUserGoodsRightsHarvest(id);
//		if (ugList != null && ugList.size() > 0) {
//			for (UserGoodsRightsHarvest gst : ugList) {
//				gst.setExpectHarvestTime(DateUtil.ChTime(gst.getExpectHarvestTime()));
//			}
//		}
		log.info("【查询权益的预计产量信息service，返回值：】" + ugList);
		log.info("【查询权益的预计产量信息结束时间：】" + (System.currentTimeMillis() - systime) / 1000f + "秒");
		return ugList;
	}

	/**
	 * 获取权益详情中的对话
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param type
	 *            type
	 * @return List<UserGoodsRightsPost>
	 */
	@Override
	public List<UserGoodsRightsPost> findUserGoodsRightsPost(String type) {
		return userRightsMapper.findUserGoodsRightsPost(type);
	}

	/**
	 * 我的权益首页
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param pam
	 *            pam
	 * @return List<RightConfig>
	 */
	@Override
	public List<RightConfig> getGoodsRightList(Map<String, Object> pam) {
		long systime = System.currentTimeMillis();
		log.info("【我的权益首页service方法进入时间】" + DateUtil.getTime());
		log.info("【我的权益首页service方法传入的参数 pam：】" + pam);
		// app获取所有的根分类
		List<RightConfig> rightConfigList = userRightsMapper.getClassId("00");
		if (rightConfigList != null && rightConfigList.size() > 0) {
			// 这个是用于判断查询 此用户下“所有”分类的数据 如果数据为空 则返回null 说明分类没有任何数据
			pam.put("classId", null);
			List<UserGoodsRights> userGoodsRightsList = userRightsMapper.getGoodsRightList(pam);
			if (userGoodsRightsList == null || userGoodsRightsList.size() == 0) {
				return null;
			} else {
				for (int i = 0; i < rightConfigList.size(); i++) {
					RightConfig rcf = rightConfigList.get(i);
					pam.put("classId", goodsManager.getClassIdByPid(rcf.getClassId()));
					// 查询此用户下“此”分类下面的所有的数据
					userGoodsRightsList = userRightsMapper.getGoodsRightList(pam);
					if (userGoodsRightsList != null && userGoodsRightsList.size() > 0) {
						rcf.setUserGoodsRights(userGoodsRightsList);
					}
				}
			}
		}
		log.info("【我的权益首页service，返回值：】" + rightConfigList);
		log.info("【我的权益首页结束时间：】" + (System.currentTimeMillis() - systime) / 1000f + "秒");
		return rightConfigList;
	}

	/**
	 * 查询每个大类的统计百分比
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param userId
	 *            userId
	 * @return List<RightConfig>
	 */
	public List<RightConfig> getClassPercentage(int userId) {
		long systime = System.currentTimeMillis();
		log.info("【查询每个大类的统计百分比service方法进入时间】" + DateUtil.getTime());
		log.info("【查询每个大类的统计百分比service方法传入的参数 userId：】" + userId);
		List<RightConfig> rightConfigList = userRightsMapper.getClassPercentage(userId);
		int total = 0;
		for (int i = 0; i < rightConfigList.size(); i++) {
			RightConfig rightConfig = rightConfigList.get(i);
			if (rightConfig.getAlltotal() == 0) {
				rightConfig.setPercentage(0);
			} else {
				if (rightConfig.getTotal() == 0) {
					rightConfig.setPercentage(0);
				} else {
					if (i == rightConfigList.size() - 1) { // 最后一个百分比肯定是最大的
															// （数据库根据百分比从小到大进行排序）
						if (total != 0) {
							rightConfig.setPercentage(100 - total);
						}
					} else {
						total = total + rightConfig.getPercentage();
					}
				}
			}
		}
		log.info("【查询每个大类的统计百分比service，返回值：】" + rightConfigList);
		log.info("【查询每个大类的统计百分比结束时间：】" + (System.currentTimeMillis() - systime) / 1000f + "秒");
		return rightConfigList;
	}

	/**
	 * 查询用户权益总数
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param userId
	 *            userId
	 * @return int
	 */
	@Override
	public int getRightNum(int userId) {
		long systime = System.currentTimeMillis();
		log.info("【查询用户权益总数service方法进入时间】" + DateUtil.getTime());
		log.info("【查询用户权益总数service方法传入的参数 userId：】" + userId);
		Integer rightSum = userRightsMapper.getRightNum(userId);
		log.info("【查询用户权益总数service，rightSum ：】" + rightSum);
		if (rightSum == null) {
			log.info("【查询用户权益总数service，如果rightSum为null则 返回值：】" + 0);
			log.info("【查询用户权益总数结束时间：】" + (System.currentTimeMillis() - systime) / 1000f + "秒");
			return 0;
		} else {
			log.info("【查询用户权益总数service，返回值：】" + rightSum);
			log.info("【查询用户权益总数结束时间：】" + (System.currentTimeMillis() - systime) / 1000f + "秒");
			return rightSum;
		}

	}

	/**
	 * 根据orderGoodsid查询 权益详情
	* @author 葛欢欢
	* @version 2017.11.30 16:40 
	* @param orderGoodsId orderGoodsId
	* @return UserGoodsRights
	 */
	@Override
	public UserGoodsRights getRightByOrderGoodsId(int orderGoodsId) {
		// TODO Auto-generated method stub
		return userRightsMapper.getRightByOrderGoodsId(orderGoodsId);
	}

	/**
	 * wap查询所有的根分类
	 * @return List<RightConfig>
	 */
	public List<RightConfig> getWapClassId() {
		// TODO Auto-generated method stub
		return userRightsMapper.getClassId("01");
	}
}
